package com.hzw.saas.web.sso.util;

import cn.hutool.core.util.StrUtil;
import com.hzw.saas.common.config.util.RedisUtil;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

import java.util.List;
import java.util.Objects;

import static com.hzw.saas.web.sso.util.Constants.REDIS_OAUTH_PREFIX;

/**
 * @author sonam
 * @sine 2021/11/11 3:02 下午
 */
public class OauthUtils {

    public static void setCodeToken(String clientId, String code, OAuth2AccessToken oAuth2AccessToken) {
        RedisUtil.set(buildTokenKeyByCode(code, clientId), oAuth2AccessToken, 5 * 60);
    }

    public static OAuth2AccessToken getCodeToken(String clientId, String code) {
        return RedisUtil.get(buildTokenKeyByCode(code, clientId));
    }

    public static void delCodeToken(String clientId, String code) {
        RedisUtil.del(buildTokenKeyByCode(code, clientId));
    }

    private static String buildTokenKeyByCode(String code, String clientId) {
        return StrUtil.format("{}:{}:{}", REDIS_OAUTH_PREFIX, code, clientId);
    }

    public static boolean checkRedirectUri(List<String> redirectUris, String redirect) {
        if (StrUtil.isBlank(redirect) || !(redirect.startsWith("https://") || redirect.startsWith("http://"))) {
            return false;
        }
        redirect = redirect.split("\\?")[0];
        if (redirect.endsWith(StrUtil.SLASH)) {
            redirect = redirect.substring(0, redirect.length() - 1);
        }
        for(String red : redirectUris) {
            if (red.endsWith(StrUtil.SLASH)) {
                red = red.substring(0, red.length() - 1);
            }
            red = red.replace("https://", "").replace("http://", "");
            redirect = redirect.replace("https://", "").replace("http://", "");
            if(Objects.equals(red, redirect)) {
                return true;
            }
        }
        return false;
    }

}
